<?php
declare (strict_types = 1);

namespace app\superAdmin\controller;

use app\BaseController;
use app\Request;
use think\captcha\facade\Captcha;
use think\facade\Db;

class Login extends BaseController
{
    public function index(){
        if(session('user')){
            return redirect('/superadmin/index');
        }

        return view('index');
    }

    public function verify(){
        return Captcha::create();
    }

    public function verifyLogin(Request $request){
        $input = $request -> all();

        // 检测输入的验证码是否正确
        if( !captcha_check($input['code']))
        {
            return json(['code'=>0,'msg'=>'验证码错误']);
        }

        //用户名
        $res = Db::name("user")->where('username',$input['username'])->find();
        if(!isset($res)){
            return json(['code'=>0,'msg'=>'用户名错误']);
        }

        if($res['status'] == 0){
            return json(['code'=>0,'msg'=>'用户禁止登陆']);
        }

        //密码
        if(md5($input['password']) != $res['password']){
            return json(['code'=>0,'msg'=>'密码不正确']);
        }

        Db::name('user') -> where($res) -> update(['updated_at'=>time()]);

        session('user',$res);

        return json(['code'=>1,'msg'=>'登录成功']);
    }

    public function loginOut(){
        session('user',null);
        return redirect('/superAdmin/login');
    }

    public function test(){
        $data = Db::name('user')->alias('a')->field('a.*,b.role')->join("group b","a.group_id=b.id")->select();
        dd($data);
    }
}
